#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
场景化自动决策系统演示脚本
展示系统的完整功能和工作流程
"""

import os
import sys
import time
import json
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

try:
    from core.utils import color_green, color_yellow, color_red, color_blue, color_purple
    from modules.intelligence.scenario_template_engine import ScenarioTemplateEngine, ScenarioType
    from apps.scenario_auto_decision_main import ScenarioAutoDecisionSystem, OptimizationLevel
    from modules.intelligence.intelligent_decision_engine import SystemEnvironment
except ImportError as e:
    print(f"导入模块失败: {e}")
    sys.exit(1)

def print_banner():
    """打印演示横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════════════════════╗
║                        场景化自动决策系统演示                                  ║
║                    Scenario-Based Auto Decision System Demo                  ║
╚══════════════════════════════════════════════════════════════════════════════╝
    """
    color_purple(banner)

def print_section_header(title):
    """打印章节标题"""
    color_blue(f"\n{'='*60}")
    color_blue(f"  {title}")
    color_blue(f"{'='*60}")

def demo_scenario_detection():
    """演示场景检测功能"""
    print_section_header("1. 场景检测演示")
    
    color_yellow("正在初始化场景检测引擎...")
    engine = ScenarioTemplateEngine()
    
    # 创建模拟环境
    color_yellow("创建模拟系统环境...")
    mock_env = SystemEnvironment(
        distro="Windows",
        version="10.0.19041",
        architecture="x64",
        kernel_version="10.0.19041",
        cpu_count=4,
        memory_total=8 * 1024 * 1024 * 1024,  # 8GB
        listening_ports=[80, 443, 3389],
        network_interfaces=["Ethernet", "Wi-Fi"],
        security_products=["Windows Defender"],
        ssh_active=False,
        cron_active=False,
        systemd_active=False,
        selinux_enabled=False,
        apparmor_enabled=False,
        firewall_active=True
    )
    
    color_yellow("开始场景检测...")
    detection_result = engine.detect_scenario(mock_env)
    
    if detection_result:
        color_green(f"✓ 检测到场景: {detection_result.detected_scenario.value}")
        color_green(f"✓ 置信度: {detection_result.confidence_score:.2%}")
        
        if detection_result.evidence:
            color_blue("检测证据:")
            for evidence in detection_result.evidence[:3]:
                print(f"  • {evidence}")
        
        if detection_result.alternative_scenarios:
            color_blue("备选场景:")
            for scenario, confidence in detection_result.alternative_scenarios[:2]:
                print(f"  • {scenario.value}: {confidence:.2%}")
    else:
        color_red("❌ 场景检测失败")
    
    return detection_result

def demo_template_selection(scenario_type):
    """演示模板选择功能"""
    print_section_header("2. 场景模板选择演示")
    
    color_yellow("正在选择场景模板...")
    system = ScenarioAutoDecisionSystem()
    
    template = system.select_scenario_template(scenario_type)
    
    if template:
        color_green(f"✓ 选择模板: {template.get('name', '未知')}")
        color_blue(f"描述: {template.get('description', '无描述')}")
        
        features = template.get('features', [])
        if features:
            color_blue(f"包含功能: {len(features)} 个")
            for feature in features[:5]:  # 显示前5个功能
                print(f"  • {feature.get('name', '未知功能')}")
            if len(features) > 5:
                print(f"  ... 还有 {len(features) - 5} 个功能")
    else:
        color_red("❌ 模板选择失败")
    
    return template

def demo_scenario_analysis(scenario_type):
    """演示场景分析功能"""
    print_section_header("3. 场景分析演示")
    
    color_yellow("正在进行场景分析...")
    system = ScenarioAutoDecisionSystem()
    
    analysis_result = system.run_scenario_analysis(
        scenario_type=scenario_type,
        max_recommendations=5,
        risk_threshold=0.7,
        dry_run=True
    )
    
    if analysis_result:
        color_green("✓ 场景分析完成")
        
        # 显示分析结果
        if 'recommendations' in analysis_result:
            recommendations = analysis_result['recommendations']
            color_blue(f"生成推荐: {len(recommendations)} 个")
            for i, rec in enumerate(recommendations[:3], 1):
                print(f"  {i}. {rec.get('name', '未知推荐')}")
        
        if 'risk_assessment' in analysis_result:
            risk_info = analysis_result['risk_assessment']
            color_blue(f"风险评估: {risk_info.get('overall_risk', '未知')}")
        
        if 'optimization' in analysis_result:
            opt_info = analysis_result['optimization']
            color_blue(f"优化建议: {len(opt_info.get('suggestions', []))} 条")
    else:
        color_red("❌ 场景分析失败")
    
    return analysis_result

def demo_one_click_deploy(scenario_type):
    """演示一键部署功能"""
    print_section_header("4. 一键部署演示")
    
    color_yellow("正在执行一键部署...")
    system = ScenarioAutoDecisionSystem()
    
    deploy_result = system.one_click_deploy(scenario_type, dry_run=True)
    
    if deploy_result and deploy_result.get('success'):
        color_green("✓ 一键部署成功 (模拟模式)")
        
        if 'deployed_features' in deploy_result:
            features = deploy_result['deployed_features']
            color_blue(f"部署功能: {len(features)} 个")
            for feature in features[:5]:
                print(f"  • {feature}")
            if len(features) > 5:
                print(f"  ... 还有 {len(features) - 5} 个功能")
        
        if 'message' in deploy_result:
            color_blue(f"部署信息: {deploy_result['message']}")
    else:
        color_red("❌ 一键部署失败")
        if deploy_result and 'error' in deploy_result:
            color_red(f"错误信息: {deploy_result['error']}")
    
    return deploy_result

def demo_available_scenarios():
    """演示可用场景列表"""
    print_section_header("5. 可用场景列表")
    
    color_yellow("获取可用场景...")
    system = ScenarioAutoDecisionSystem()
    
    scenarios = system.list_available_scenarios()
    
    if scenarios:
        color_green(f"✓ 发现 {len(scenarios)} 个可用场景:")
        for i, scenario in enumerate(scenarios, 1):
            scenario_name = scenario.get('name', '未知场景')
            scenario_desc = scenario.get('description', '无描述')
            print(f"  {i}. {scenario_name}")
            print(f"     {scenario_desc}")
    else:
        color_red("❌ 未找到可用场景")

def demo_template_export(scenario_type):
    """演示模板导出功能"""
    print_section_header("6. 模板导出演示")
    
    color_yellow("正在导出场景模板...")
    system = ScenarioAutoDecisionSystem()
    
    export_file = f"exported_template_{scenario_type.value}.json"
    
    try:
        system.export_scenario_template(scenario_type, export_file)
        
        if os.path.exists(export_file):
            color_green(f"✓ 模板导出成功: {export_file}")
            
            # 显示文件大小
            file_size = os.path.getsize(export_file)
            color_blue(f"文件大小: {file_size} 字节")
            
            # 清理导出文件
            os.remove(export_file)
            color_yellow("清理临时文件完成")
        else:
            color_red("❌ 导出文件未找到")
    except Exception as e:
        color_red(f"❌ 模板导出失败: {e}")

def demo_performance_metrics():
    """演示性能指标"""
    print_section_header("7. 性能指标演示")
    
    color_yellow("测试系统性能...")
    
    # 测试场景检测性能
    start_time = time.time()
    engine = ScenarioTemplateEngine()
    mock_env = SystemEnvironment(
        distro="Ubuntu",
        version="20.04",
        architecture="x64",
        kernel_version="5.4.0-74-generic",
        cpu_count=2,
        memory_total=4 * 1024 * 1024 * 1024,  # 4GB
        listening_ports=[22, 80, 443],
        network_interfaces=["eth0"],
        security_products=[],
        ssh_active=True,
        cron_active=True,
        systemd_active=True,
        selinux_enabled=False,
        apparmor_enabled=True,
        firewall_active=False
    )
    
    detection_result = engine.detect_scenario(mock_env)
    detection_time = time.time() - start_time
    
    color_green(f"✓ 场景检测耗时: {detection_time:.3f} 秒")
    
    # 测试模板选择性能
    start_time = time.time()
    system = ScenarioAutoDecisionSystem()
    template = system.select_scenario_template(ScenarioType.PERSONAL_TESTING)
    selection_time = time.time() - start_time
    
    color_green(f"✓ 模板选择耗时: {selection_time:.3f} 秒")
    
    # 显示内存使用情况
    try:
        import psutil
        process = psutil.Process()
        memory_info = process.memory_info()
        color_blue(f"内存使用: {memory_info.rss / 1024 / 1024:.2f} MB")
    except ImportError:
        color_yellow("psutil 未安装，无法显示内存信息")

def main():
    """主演示函数"""
    print_banner()
    
    color_purple("欢迎使用场景化自动决策系统演示！")
    color_purple("本演示将展示系统的核心功能和完整工作流程。")
    
    try:
        # 1. 场景检测演示
        detection_result = demo_scenario_detection()
        
        if detection_result:
            scenario_type = detection_result.detected_scenario
        else:
            scenario_type = ScenarioType.PERSONAL_TESTING
            color_yellow(f"使用默认场景: {scenario_type.value}")
        
        # 2. 模板选择演示
        template = demo_template_selection(scenario_type)
        
        # 3. 场景分析演示
        analysis_result = demo_scenario_analysis(scenario_type)
        
        # 4. 一键部署演示
        deploy_result = demo_one_click_deploy(scenario_type)
        
        # 5. 可用场景列表
        demo_available_scenarios()
        
        # 6. 模板导出演示
        demo_template_export(scenario_type)
        
        # 7. 性能指标演示
        demo_performance_metrics()
        
        # 演示总结
        print_section_header("演示总结")
        
        success_count = 0
        total_tests = 4
        
        if detection_result:
            success_count += 1
        if template:
            success_count += 1
        if analysis_result:
            success_count += 1
        if deploy_result and deploy_result.get('success'):
            success_count += 1
        
        success_rate = (success_count / total_tests) * 100
        
        color_green(f"✓ 演示完成！成功率: {success_rate:.1f}% ({success_count}/{total_tests})")
        
        if success_rate >= 75:
            color_green("🎉 系统运行良好，所有核心功能正常工作！")
        elif success_rate >= 50:
            color_yellow("⚠️ 系统基本正常，但有部分功能需要优化。")
        else:
            color_red("❌ 系统存在问题，需要进一步调试。")
        
        color_purple("\n感谢使用场景化自动决策系统演示！")
        color_purple("如需了解更多功能，请查看用户界面:")
        color_purple("python apps/scenario_ui.py")
        
    except KeyboardInterrupt:
        color_yellow("\n演示被用户中断")
    except Exception as e:
        color_red(f"\n演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()